package com.example.knowledgeget1.KnowtCommon.Service;

import com.example.knowledgeget1.ChatCommon.Repository.NodeTypeRepository;
import com.example.knowledgeget1.KnowtCommon.Entity.KnowStatus;
import com.example.knowledgeget1.KnowtCommon.Entity.StatusId;
import com.example.knowledgeget1.KnowtCommon.Repository.KnowStatusRepository;
import com.example.knowledgeget1.ChatCommon.Entity.NodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class KnowStatusService {
    @Autowired
    private KnowStatusRepository knowStatusRepository;
    @Autowired
    private KnowinService knowinService;
    @Autowired
    private NodeTypeRepository nodeTypeRepository;

    public List<KnowStatus> getKnowStatusByStuAndCourse(Long stuId, Long courseId) {
        List<Long> knowIds = knowinService.getKnowIdsByCourseId(courseId);

        return knowStatusRepository.findByIdIn(knowIds.stream()
                .map(knowId -> new StatusId(stuId, knowId))
                .collect(Collectors.toList()));
    }

    public List<String> getKnowledgeNamesByIds(List<Long> knowIds) {
        return nodeTypeRepository.findByIdIn(knowIds).stream()
                .map(NodeType::getName)
                .collect(Collectors.toList());
    }

    public void learnKnowledge(Map<String, Object> request) {
        Long stuId = Long.parseLong(request.get("stuId").toString());
        List<Map<String, String>> knowledgeList = (List<Map<String, String>>) request.get("knowledgeList");

        List<String> knowledgeNames = knowledgeList.stream()
                .map(map -> map.get("name"))
                .toList();
        List<NodeType> nodeTypes = nodeTypeRepository.findIdsByNameIn(knowledgeNames);
        List<Long> knowIds = nodeTypes.stream()
                .map(NodeType::getId)
                .toList();
        knowStatusRepository.batchUpdateLearnStatus(stuId, knowIds);
    }

    public void unlearnKnowledge(Map<String, Object> request) {
        Long stuId = Long.parseLong(request.get("stuId").toString());
        List<Map<String, String>> knowledgeList = (List<Map<String, String>>) request.get("knowledgeList");
        List<String> knowledgeNames = knowledgeList.stream()
                .map(map -> map.get("name"))
                .toList();
        List<NodeType> nodeTypes = nodeTypeRepository.findIdsByNameIn(knowledgeNames);
        List<Long> knowIds = nodeTypes.stream()
                .map(NodeType::getId)
                .toList();
        knowStatusRepository.batchUpdateUnLearnStatus(stuId, knowIds);
    }
}
